/*
 *		source/mainview/mainview.js - Main View
 */

/* Tegi's Commander - A file manager for Palm WebOS
 * Copyright (C) 2011 Timo Tegtmeier
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 3
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

enyo.kind({
	name:			"MainView",
	kind:			"VFlexBox",

	activated:		true,

	kCookieName:	"comtegistuffappcommander",

	components:	[{
		kind:	"SlidingPane",
		flex:	1,
		components:	[{
			name:			"left",
			kind:			"FolderView",
			flex:			1,
			isLeft:			true,
			onOpenFile:		"openFile",
			onEditFile:		"editFile",
			onCopyFile:		"copyFile",
			onMoveFile:		"moveFile",
			onIsEditable:	"getIsEditable",
			onIsImage:		"getIsImage",
			onSwitch:		"switchPaths",
			onError:		"showError"
		}, {
			name:			"right",
			kind:			"FolderView",
			flex:			1,
			isLeft:			false,
			onOpenFile:		"openFile",
			onEditFile:		"editFile",
			onCopyFile:		"copyFile",
			onMoveFile:		"moveFile",
			onIsEditable:	"getIsEditable",
			onIsImage:		"getIsImage",
			onSwitch:		"switchPaths",
			onError:		"showError"
		}]
	}, {
		name:		"licenseDialog",
		kind:		"LicenseDialog"
	}, {
		name:		"helpDialog",
		kind:		"HelpDialog"
	}, {
		name:		"prefsDialog",
		kind:		"PreferencesDialog"
	}, {
		kind: 		"Dialog",
		name:		"errorDialog",
		lazy:		false,
		components: [{
			name:		"errorMessage",
			style:		"margin: 25px"
		}, {
			kind: 	"HFlexBox",
			pack: "center",
			components: [{
	            kind:		"Button",
				caption:	$L("OK"),
				className:	"enyo-button-affirmative",
				style:		"margin: 0px 25px 10px 25px",
				flex:		1,
				onclick:	"closeDialog"
			}]
		}]
	}, {
		kind:					"AppMenu",
		components:				[{
			kind:				"EditMenu"
		}, {
			caption:			$L("License"),
			onclick:			"openLicense"
		}, {
			caption:			$L("Preferences"),
			onclick:			"openPrefs"
		}, {
			caption:			$L("Help"),
			onclick:			"openHelp"
		}]
	}, {
		name:		"fileService",
		kind:		"PalmService",
		service:	"palm://com.tegistuff.app.commander.service/"
	}, {
		name:		"appMgr",
		kind: 		"PalmService",
		service:	"palm://com.palm.applicationManager/",
		method:		"open"
	}, {
		kind:					"ApplicationEvents",
		onWindowActivated:		"windowActivated",
		onWindowDeactivated:	"windowDeactivated",
		onUnload:				"saveSettings"
	}],

	//
	// Events
	//

	showError: function(sender, error) {
		this.$.errorMessage.setContent(error || $L("File operation failed."));
		this.$.errorDialog.open();
	},

	closeDialog: function(sender, event) {
		this.$.errorDialog.close();
	},

	openFile: function(sender, file) {
		if(this.getIsTextFile(this, file)) {
			this.editFile(this, file);
		} else if(this.getIsImage(this, file)) {
			enyo.windows.activate("source/imageviewer/index.html", "imageviewer", {
				path: file
			});
		} else {
			this.$.appMgr.call({ target: file });
		}
	},

	editFile: function(sender, file) {
		enyo.windows.activate("source/editor/index.html", "editor", {
			path: file
		});
	},

	copyFile: function(sender, file) {
		this.$.fileService.call({
			fromPath:	sender.joinPath(file),
			toPath:		this.getOppositeView(sender).getPath()
		}, {
			method:		"copy",
			onSuccess:	"refreshFileLists",
			onFailure:	"copyFailed"
		});
	},

	copyFailed: function() {
		this.showError(this, $L("Unable to copy selected file"));
	},

	moveFile: function(sender, file) {
		this.$.fileService.call({
			fromPath:	sender.joinPath(file),
			toPath:		this.getOppositeView(sender).joinPath(file)
		}, {
			method:		"rename",
			onSuccess:	"refreshFileLists",
			onFailure:	"moveFailed"
		});
	},

	moveFailed: function() {
		this.showError(this, $L("Unable to move selected file"));
	},

	switchPaths: function(sender) {
		var lPath = sender.getPath();
		var opposite = this.getOppositeView(sender);
		sender.setPath(opposite.getPath());
		opposite.setPath(lPath);
	},

	getIsTextFile: function(sender, filename) {
		return (/.*\.js|.*\.json/.test(filename) || /.*\.txt/.test(filename));
	},

	getIsEditable: function(sender, filename) {
		return (this.getIsTextFile(sender, filename) || /.*\.htm|.*\.html/.test(filename));
	},

	getIsImage: function(sender, filename) {
		return (/.*\.jpg/.test(filename) || /.*\.jpeg/.test(filename) || /.*\.png/.test(filename) || /.*\.gif/.test(filename) || /.*\.bmp/.test(filename));
	},

	//
	// Menu handling
	//

	openHelp: function() {
		enyo.asyncMethod(this, function() {
			this.$.helpDialog.openAtCenter();
		});
	},

	openPrefs: function() {
		enyo.asyncMethod(this, function() {
			this.$.prefsDialog.openAtCenter();
		});
	},

	openLicense: function() {
		enyo.asyncMethod(this, function() {
			this.$.licenseDialog.openAtCenter();
		});
	},

	//
	// Helper functions
	//

	getOppositeView: function(view) {
		if(view.isLeft) {
			return this.$.right;
		} else {
			return this.$.left;
		}
	},

	refreshFileLists: function() {
		this.$.left.refreshFileList();
		this.$.right.refreshFileList();
	},

	saveSettings: function(sender, event) {
		var settings = this.getSettings();
		settings.left = this.$.left.path;
		settings.right = this.$.right.path;
		enyo.setCookie(this.kCookieName, enyo.json.stringify(settings));
	},

	getSettings: function() {
		var cookie = enyo.getCookie(this.kCookieName);
		try {
			if(cookie) {
				return enyo.json.parse(cookie);
			}
		} catch(ex) {
			this.error("ERROR parsing cookie:", cookie);
		}
		return ({
			left:				"/media/internal",
			right:				"/media/internal",
			showGotoFolder:		false,
			showCreateFile:		false,
			showHiddenFiles:	false
		});
	},

	applySettings: function(settings, view) {
		view.setShowGotoFolder(settings.showGotoFolder);
		view.setShowCreateFile(settings.showCreateFile);
		view.setShowHiddenFiles(settings.showHiddenFiles);
		view.setPath(settings[view.name]);
	},

	settingsChanged: function(settings) {
		settings.left = this.$.left.path;
		settings.right = this.$.right.path;
		enyo.setCookie(this.kCookieName, enyo.json.stringify(settings));

		this.applySettings(settings, this.$.left);
		this.applySettings(settings, this.$.right);
	},

	windowDeactivated: function() {
		this.activated = false;
	},

	windowActivated: function() {
		if(!this.activated) {
			this.$.left.noPunt = true;
			this.$.right.noPunt = true;
			this.refreshFileLists();
			this.activated = true;
		}
	},

	//
	// Initialization
	//

	create: function() {
		this.inherited(arguments);

		this.settingsChanged = enyo.bind(this, this.settingsChanged);
		enyo.keyboard.setResizesWindow(false);

		var settings = this.getSettings();
		this.applySettings(settings, this.$.left);
		this.applySettings(settings, this.$.right);
	}
});
